<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    @ok="onButtonOkClick"
    @cancel="removeFile"
  >
    <a-upload-dragger
      :file-list="fileList"
      name="file"
      :maxCount="1"
      accept=".xls,.xlsx,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'"
      :custom-request="upload"
      @change="changeFile"
      @remove="removeFile"
    >
      <p class="ant-upload-drag-icon">
        <CloudUploadOutlined />
      </p>
      <p class="ant-upload-text">Click or drag file to this area to upload</p>
      <p class="ant-upload-hint"> 请点击或拖拽上传危险源导则库excel文件 </p>
    </a-upload-dragger>
    <div>
      <span style="margin: 10px">导入方式：</span>
      <a-radio-group v-model:value="iscover" style="margin-top: 20px">
        <a-radio :value="true">清空原有并覆盖</a-radio>
        <a-radio :value="false">追加</a-radio>
      </a-radio-group>
    </div>
    <div>
      <span style="margin: 10px">是否为重大危险源：</span>
      <a-radio-group v-model:value="ismajor" style="margin-top: 20px">
        <a-radio :value="true">是</a-radio>
        <a-radio :value="false">否</a-radio>
      </a-radio-group>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { uploadApi } from '/@/api/platform/upload';
  import { importDangerDb } from '/@/api/ehs/templateHazard';
  import { CloudUploadOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import XLSX from 'xlsx';
  const { createMessage } = useMessage();
  export default defineComponent({
    components: { BasicModal, CloudUploadOutlined },
    emits: ['success'],
    name: 'ImportTemplateHazard',
    setup(_, { emit }) {
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const fileId = ref();
      const dataId = ref();
      const fileList = ref([]);
      const iscover = ref(false);
      const ismajor = ref(false);
      const [register, { closeModal }] = useModalInner((data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
          }
        }
      });
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      function upload(info) {
        const fileType = info.file.name.split('.').pop();
        // 获取文件类型,如果是excel文件则上传,否则提示文件格式错误
        if (fileType === 'xlsx' || fileType === 'xls') {
          uploadApi({ system: 'ehs', file: info.file, module: 'attachment' })
            .then((res) => {
              if (res.data.data.success) {
                fileId.value = res.data.data.fileid;
                createMessage.success('上传成功');
                info.onSuccess(res.data, info);
              } else {
                fileId.value = undefined;
                createMessage.error('上传失败,请稍后重试');
                fileList.value[0].status = 'error';
              }
            })
            .catch((err) => {
              fileId.value = undefined;
              createMessage.error('上传失败,请稍后重试');
              fileList.value[0].status = 'error';
            });
        } else if (fileType !== 'xlsx' && fileType !== 'xls') {
          fileId.value = undefined;
          createMessage.error('文件格式不符,请上传excel文件');
          fileList.value[0].status = 'error';
        }
      }
      function removeFile() {
        // 移除上传的文件,清空文件数据
        fileId.value = undefined;
        fileList.value = [];
      }

      function onButtonOkClick() {
        console.log(fileId.value, 'fileId');
        let result = [];
        // 点击确认后,如果fileId为空,说明没有上传有效的文件
        if (fileId.value == undefined || fileId.value == null) {
          createMessage.error('无有效上传文件,请确认后重试');
          return;
        }
        // 如果有fileId说明有上传成功的excel文件,则进行导入
        importDangerDb({
          fileid: fileId.value,
          hdbcd: dataId.value,
          iscover: iscover.value,
          ismajor: ismajor.value,
        })
          .then((res) => {
            if (!res) {
              createMessage.success('导入成功');
              emit('success');
              closeModal();
            } else {
              createMessage.error('导入失败,请稍后重试');
            }
          })
          .catch((e) => {
            console.log(e);
          });
      }

      function changeFile(e) {
        fileList.value = e.fileList;
      }
      return {
        iscover,
        register,
        fileId,
        changeFile,
        closeModal,
        displayModuleTitle,
        upload,
        removeFile,
        fileList,
        onButtonOkClick,
        ismajor,
      };
    },
  });
</script>
